<!DOCTYPE html>
<html>

<head>
  <title>
    <%= title %>
  </title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
  <script type="text/javascript" src="/socket.io/socket.io.js"></script>
  <style>
    #app {
      width: 600px;
      height: 400px;
      background: #ccc;
    }

    .main {
      height: 40%;
    }

    .message {
      height: 30%;
      background: yellow;
    }

    .users {
      height: 30%;
      background: green;
    }
  </style>
</head>

<body>
  <% if(!username){ %>
  <div id="user">
    <form action="/" method="post">
      <p>用户名：<input type="text" name="username" > </p>
      <p>密码：<input type="password" name="pwd" > </p>
      <input type="submit" value="登录">
    </form>
  </div>
  <% } else { %>

  <div id="app">
    <div class="main"></div>
    <div class="message">
      <textarea id="content" cols="30" rows="6"></textarea>
      <button id="send">发送</button>
    </div>
    <div class="users"></div>
  </div>
  <script>
    const socket = io.connect('http://localhost:3000');
    document.querySelector('#send')
      .addEventListener('click', (e, event) => {
        const content = document.querySelector('#content').value;
        socket.emit('message', {
          content
        });
      });
    socket.on('broadcast', data => {
      const p = document.createElement('p');
      p.innerText = data.content;
      document.querySelector('.main')
        .appendChild(p);
    });
    socket.on('all', data => {
      data.forEach(e => {
        const p = document.createElement('p');
        p.innerText = e.content;
        document.querySelector('.main')
          .appendChild(p);
        })
      });
      socket.on('users', users => {
        const userDiv = document.querySelector('.users');
        userDiv.innerHTML = '';
        users.forEach(username => {
          const p = document.createElement('p');
          p.innerText = username;
          userDiv.appendChild(p);
      })
    })
  </script>
  <% } %>

</body>

</html>